/**
 * 已知如下数组菜单，要求输出树形菜单结构,递归代码实现?
    [
        { id: 1, parent: null, name: '菜单1' },
        { id: 2, parent: 1, name: '菜单1-1' },
        { id: 3, parent: 1, name: '菜单1-2' },
        { id: 4, parent: null, name: '菜单2' },
        { id: 5, parent: 4, name: '菜单2-1' },
    ]

  树形菜单
  [
    {
        id: 1,
        parent: null,
        name: '菜单1',
        children: [
            { id: 2, parent: 1, name: '菜单1-1' },
            { id: 3, parent: 1, name: '菜单1-2' },
        ]
    },
    {
        id: 4,
        parent: null,
        name: '菜单2',
        children: [
            { id: 5, parent: 4, name: '菜单2-1' }
        ]
    }
]
 */
const list = [
    { id: 1, parent: null, name: '菜单1' },
    { id: 2, parent: 1, name: '菜单1-1' },
    { id: 3, parent: 1, name: '菜单1-2' },
    { id: 4, parent: null, name: '菜单2' },
    { id: 5, parent: 4, name: '菜单2-1' },
]

const getTreeMenu = (rootList, id, list) => {
    for (const item of rootList) {
        if (item.parent == id) {
            // 找到一级节点
            list.push(item)
        }
    }
    for (const ele of list) {
        ele.children = []
        getTreeMenu(rootList, ele.id, ele.children)
        // 优化删除空数组节点
        if (ele.children.length == 0) {
            delete ele.children
        }
    }

    return list
}

let menuList = getTreeMenu(list, null, [])
console.log(menuList)
